package com.sun.hunk.struts.action;

import com.sun.hunk.hibernate.dao.InvoiceDAO;
import com.sun.hunk.hibernate.domain.Charge;
import com.sun.hunk.hibernate.domain.Invoice;
import com.sun.hunk.hibernate.domain.impl.DomainFactory;
import com.sun.hunk.struts.HunkDispatchAction;
import com.sun.hunk.struts.form.InvoiceForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author sunil
 */
public class InvoiceAction extends HunkDispatchAction {

    public ActionForward display(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        InvoiceForm invoiceForm = (InvoiceForm) form;
        Invoice invoice = new InvoiceDAO().findById(invoiceForm.getInvoice().getId());
        invoiceForm.setInvoice(invoice);
        request.getSession().setAttribute("invoiceForm", invoiceForm);
        return mapping.findForward(SUCCESS);
    }

    public ActionForward newInvoice(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getSession().setAttribute("invoiceForm", new InvoiceForm());
        return mapping.findForward(SUCCESS);
    }

    public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        InvoiceForm invoiceForm = (InvoiceForm) form;
        new InvoiceDAO().saveOrUpdate(invoiceForm.getInvoice());
        setMessage(request, "Invoice saved successfully !");
        return mapping.findForward(SUCCESS);
    }

    public ActionForward addCharge(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        InvoiceForm invoiceForm = (InvoiceForm) form;
        Charge charge = DomainFactory.getCharge();
        invoiceForm.getInvoice().addCharge(charge);
        setMessage(request, "New charge is added");
        return mapping.findForward(SUCCESS);
    }

    public ActionForward removeCharge(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        InvoiceForm invoiceForm = (InvoiceForm) form;
        Long id = Long.parseLong(request.getParameter("charge_id"));
        Charge charge = DomainFactory.getCharge();
        charge.setId(id);
        setMessage(request, "Charge is deleted.");
        invoiceForm.getInvoice().getCharges().remove(charge);
        return mapping.findForward(SUCCESS);
    }
}
